package com.ruoyi.framework.interceptor;

import com.ruoyi.common.utils.RequestInfo;
import com.ruoyi.framework.utils.sqResponseStatus;
import com.ruoyi.common.thread.ReqThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.common.constant.ServerConstants.MANAGE_REQ_FLAG;


/**
 * 仕仟管理端-全局拦截器
 *
 */
@Slf4j
@Component
public class ShiqianManagerInterceptor implements HandlerInterceptor {
    private StringRedisTemplate redisTemplate;

    public ShiqianManagerInterceptor(){
    }

    public ShiqianManagerInterceptor(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     *传入token字符串，截取存储在redis的key
     * @param token
     * @return
     */
    public String subTokenToGetKey(String token){
        String[] tokenArr = token.split(":");

        String tokenKey = tokenArr[0] + ":" + tokenArr[1];

        return tokenKey;
    }



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        com.alibaba.fastjson2.JSONObject result = new com.alibaba.fastjson2.JSONObject();

        //2.从请求头中获取token
        String token = request.getHeader("ClientAuthorization");
        String RequestFlag = request.getHeader("RequestFlag");

        ReqThreadLocalUtil.setReq(new RequestInfo(RequestFlag));

        if (MANAGE_REQ_FLAG.equals(RequestFlag)){
            // 不拦截管理端的请求
            return true;
        }
        if (token != null && !token.isEmpty()){
                //从redis中查询当前token是否存在，若不存在，说明已过期，响应401并拦截
                //获取token串的第二个":"前的内容，这是登录的账号，也是对应的key
                //token串格式：CLIENT:当前用户账号:uuid
                String tokenKey = subTokenToGetKey(token);
                String getToken = redisTemplate.opsForValue().get(tokenKey);


                if (getToken == null || !(getToken.equals(token))){
                    result.put("code", sqResponseStatus.UNAUTHORIZED.getStatusCode());
                    result.put("msg","token已过期！请重新登录！");

                    // 设置响应的内容类型为JSON
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(String.valueOf(result));
                    return false;
                }
                return true;
        }else {
            //token异常，直接拦截并响应8889
            result.put("code",sqResponseStatus.TOKEN_ERROR.getStatusCode());
            result.put("msg","token不存在或异常！请重新登录！");

            // 设置响应的内容类型为JSON
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(String.valueOf(result));
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理之后但在视图渲染之前进行拦截处理
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后进行拦截处理，可用于清理资源等操作
        ReqThreadLocalUtil.removeReq();
    }
}

